import router from './index'
import nprogress from 'nprogress'
//引入进度条样式
import 'nprogress/nprogress.css'
import { useUserStore } from '@/store/modules/user'
import { useSettingStore } from '@/store/modules/setting'
import setting from '@/config/setting'
import { constRoutes, asnycRoute, anyRoute } from '@/router/constRoutes'

const whiteRouters = ['/login', '/404']

//to:你将要访问那个路由
//from:你从来个路由而来
//next:路由的放行函数
router.beforeEach(async (to, from, next) => {
  nprogress.start()
  let userStore = useUserStore()
  let settingStore = useSettingStore()
  
  if (!setting.loginIntercept) {
    console.log(settingStore.outLineRouterLoaded, [...asnycRoute, anyRoute]);

    if (!settingStore.outLineRouterLoaded) {
      settingStore.outLineRouterLoaded = true
      
      userStore.menuRoutes = [...constRoutes, ...asnycRoute, anyRoute]
      ;[...asnycRoute, anyRoute].forEach((route: any) => {
        router.addRoute(route)
      })
    }
    next()
    return
  }

  if (userStore.token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (userStore.hasUserInfo) {
        //放行
        next()
      } else {
        //如果没有用户信息,在守卫这里发请求获取到了用户信息再放行
        //获取用户信息
        let a = await userStore.userInfo()
        //放行
        //万一:刷新的时候是异步路由,有可能获取到用户信息、异步路由还没有加载完毕,出现空白的效果
        next({ ...to })
      }
    }
  } else {
    if (whiteRouters.includes(to.path)) {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
  // next()
})

router.afterEach((to, from) => {
  nprogress.done()
})
